

package com.classload.apigateway;


import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;


//1.类名为配置文件的 Key+RoutePredicateFactory 继承 AbstractRoutePredicateFactory
//2.范型为配置类
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {


    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    //接收值的顺序
    public List<String> shortcutFieldOrder() {
        //顺序必须一致
        return Arrays.asList("minAge", "maxAge");
    }
//    断言逻辑

    public Predicate<ServerWebExchange> apply(final Config config) {

        return serverWebExchange -> {
            String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            if (StringUtils.isEmpty(ageStr)) {
                return false;
            }
            Integer age = Integer.parseInt(ageStr);
            return age < config.maxAge && age > config.minAge;
        };
    }

    //接收值的配置类
    @Data
    public static class Config {
        private Integer minAge;
        private Integer maxAge;
    }
}
